package qingxin.servlet.admin.information;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import qingxin.dao.InformationDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.Information;

@WebServlet("/admin/information/add")
public class AddInformationServlet extends AdminServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private InformationDAO informationDAO;
	
	public AddInformationServlet(){
		super();
		informationDAO = DAOFactory.getInformationDAO();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			String informationS = request.getParameter("information");
			JSONObject jsonInformation = new JSONObject(informationS);
			
			Information information = new Information();
			information.setTitle(jsonInformation.getString("title"));
			information.setContent(jsonInformation.getString("content"));
			information.setStartTime(jsonInformation.getString("start"));
			information.setEndTime(jsonInformation.getString("end"));
			information.setPhotoID(jsonInformation.getInt("pid"));
			
			informationDAO.add(information);
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
